package com.neuedu.web.servlet;

import com.neuedu.web.dao.RoleDao;
import com.neuedu.web.dao.UserDao;
import com.neuedu.web.entity.Role;
import com.neuedu.web.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @auth 金山老师
 * title:   书籍代码
 * creatime: 2022-10-19 11:31
 * 描述 :
 */
@WebServlet(value = "/role")
public class RoleServlet extends HttpServlet {
    RoleDao dao = new RoleDao();
    UserDao userDao = new UserDao();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    /**
     *   列表： http://localhost:8080/web/role
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String type = request.getParameter("_type");
        if(type == null || "list".equals(type)){
            this.list(request,response);
        }else if("toAdd".equals(type)){
            this.toAdd(request,response);
        }else if("save".equals(type)){
            this.save(request,response);
        }else if("delete".equals(type)){
            this.deleteById(request,response);
        }else if("toEdit".equals(type)){
            this.toEdit(request,response);
        }else if("update".equals(type)){
            this.update(request,response);
        }


    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //使用requests接受参数

        //getParameter 返回字符串形式的参数

        String roleId = request.getParameter("roleId");
        String roleName = request.getParameter("roleName");


        String sql = "UPDATE  role SET `role_name` = ?  where role_id = ? ";
        try {
            int count = userDao.update(sql , roleName,roleId );

            System.out.println("count = " + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        response.sendRedirect(request.getContextPath()+"/role"); //相对路径

    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws IOException {


        try {
            String id = request.getParameter("id");
            Role role = dao.selectOne(Integer.parseInt(id));

            //共享数据
            request.setAttribute("role",role);

           //请求转发给 role/role_edit.jsp
            request.getRequestDispatcher("/role/role_edit.jsp").forward(request,response);
        }catch(Exception ex){
            ex.printStackTrace();
        }


    }

    private void deleteById(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //接收一个角色id
        String  id = request.getParameter("id");

        // 调用UserDao的删除
        int count = 0;
        try {
            count = dao.deleteById(Integer.parseInt(id));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("count = " + count);


        //重定向到UserList
        response.sendRedirect(request.getContextPath() +"/role");
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String roleName = request.getParameter("roleName");

        String sql = "INSERT INTO `role` (  `role_name`)  VALUES ( ? )  ";
        try {
            int count = dao.insert(sql ,    roleName       );

            System.out.println("count = " + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        response.sendRedirect(request.getContextPath()+"/role"); //相对路径
            // request.getRequestDispatcher("/role").forward(request,response);

    }

    /**
     * 展示添加页面
     * @param request
     * @param response
     */
    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置响应格式 为html
        response.setContentType("text/html;charset=utf8");
        // 设置响应编码
        response.setCharacterEncoding("utf-8");


        StringBuilder html = new StringBuilder();

        //action属性表示提交的路径
        html.append("  <h3>用户添加</h3>														");
        html.append("  	<form method='post' action='user?_type=save'>                                          ");
        html.append("  		                                                                    ");
        html.append("  		<table width='500' border='1' cellpadding='0' cellspacing='0'>      ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>用户名</td>                                             ");
        html.append("  				<td><input type='text' name='username'></td>                ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  					<td>密码</td>                                           ");
        html.append("  				<td><input type='password' name='password'></td>                ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>昵称</td>                                               ");
        html.append("  				<td><input type='text' name='displayname'></td>             ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  					<td>birthday</td>                                       ");
        html.append("  				<td><input type='text' name='birthday'></td>                ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>性别</td>                                               ");
        html.append("  				<td><input type='text' name='gender'></td>                  ");
        html.append("  			</tr>                                                           ");
        html.append("                                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>email</td>                                              ");
        html.append("  				<td><input type='text' name='email'></td>                   ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>telephone</td>                                          ");
        html.append("  				<td><input type='text' name='telephone'></td>               ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>lastLogintime</td>                                      ");
        html.append("  				<td><input type='text' name='lastLogintime'></td>           ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  			<td colspan='2' align='center'>    <input type='submit' value='提交'>   <input type='reset'></td>                                    ");
        html.append("  			</tr>                                                           ");
        html.append("  		</table>                                                            ");
        html.append("                                                                           ");
        html.append("  	</form>                                                                ");

        PrintWriter out = response.getWriter();
        out.write(html.toString());
        out.flush();
        out.close();


    }


    //列表的方法
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {

            String sql = " select * from role";
            Object[] params = {};
            List<Role> roleList = dao.selectList(sql, params);

            //查询出来的几个放到Request中
            request.setAttribute("roles",roleList);

            //请求转发(内部跳转)
            request.getRequestDispatcher("/role/role_list.jsp").forward(request,response);


        }catch(Exception ex){
            ex.printStackTrace();
        }

    }


}
